package my.rpc.common.codec;

import my.rpc.common.util.SerializationUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * RPC 解码器
 * @author fengbo
 * @date 2017/11/2
 */
public class RpcDecoder<T> extends ByteToMessageDecoder {

    private Class<T> genericClass;

    public RpcDecoder(Class<T> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        // 因为在ByteToMessageDecoder#channelRead中会释放该ByteBuf，所以in不需要在这里手动释放
        in.readBytes(data);
        // 将字节数据反序列化成RpcRequest对象
        out.add(SerializationUtils.deserialize(data, genericClass));
    }
}
